/*
Papr.(Beta)
Author: Subhodip Kumar<subhodip.kumar@gmail.com> (c)2012 All Rights Reserved.
*/
function DB() {
        var self = this;
        var db_ = null;
        var log_ = document.querySelector('#db-log');
        var results_ = document.querySelector('#db-results');
    	
    


        this.init = function() {
          if (window.openDatabase) {
            db_ = openDatabase("ReadingList++", "2.0", "core database for reading list", 500000);
            this.createTable();
            this.showRecords();
            return this;
          }

          results_.addEventListener('click', function(e) {
            e.preventDefault();
          }, false);
        }
        
        this.deleteitems=function(){
      	$(":checked").each(function(){
      		var id = $(this).attr('id');
      		self.deleteRecord(id);
      		});
      		chrome.extension.getBackgroundPage().user_notify("Deleted!!","");
      	};
		this.fb_share=function(){
			$(":checked").each(function(){
      		var id = $(this).attr('id');
      		  db_.transaction(function(tx) {
      				tx.executeSql('SELECT url,title FROM ReadingList WHERE id = ?;', [id],
        			function(tx, r) {
          				var object=(r.rows.item(0));
          				url=object.url;
          				title=object.title;
          				chrome.extension.getBackgroundPage().fb_init(url,title);
          				console.log("fb_init called");
       				 	});
    				}, function(e) {
      					console.log(e.message);
    				});
      		
      		});
      		//chrome.extension.getBackgroundPage().fb_init("www.exquisiteforest.com","This Exquisite Forest");
      		console.log("fb_init called");
      		};
      	//Fb test ends***********************************
        this.onError = function(tx, error) {
           log_.innerHTML = '';
          chrome.extension.getBackgroundPage().user_notify("Oops!!","You broke the app..just kidding just reopen the app.");
        };

        // select all records and display them
        this.showRecords = function() {
          results_.innerHTML = '';
          db_.transaction(function(tx) {
            tx.executeSql("SELECT * FROM ReadingList", [], function(tx, result) {
              var html = [];
              for (var i = result.rows.length-1, item = null; i >= 0; --i) {
                item = result.rows.item(i);
                //test starts
                if(!window.localStorage.getItem(item['id'].toString())){
                var pic='<img class="orange" src="bullets_orange.png" style="float:left; height: 17px;max-width: 100%; " title="Read"/>';
                }
                else {
                var pic='<img class="red" src="bullets_red.png" style="float:left; height: 17px;max-width: 100%;" title="Still Unread"/>';
                }
                //test ends
                html.push('<li class="list" id="',item['id'],'" ><div class="input"><input type="checkbox" name="chk_del" id="',item['id'],'" /></div><div class="cell" id="',item['id'],'" >',pic,'<div id="title_container"><a id="',item['id'],'"class="anchor" target="_blank" href="', item['url'],'"   style="display:block;" >',item['title'],
                    '</a></div><div id=url_container><img src="bullets_blue.png" style="height: 15px; max-width: 100%; padding-left:1px;" /><span class="shortUrl" id="',item['id'],'" >', item['shortUrl'],'</span></sdiv></div></li>');
              }
              results_.innerHTML = html.join('');
            });
          });
        };

//this function will be called from content page. it will provide the id of the span clicked.
//this has to return the content from the db corresponding page.
getPageCon = function(ID, sendResponse) {	
  db_.transaction(function(tx) {
      tx.executeSql('SELECT content FROM ReadingList WHERE id = ?;', [ID],
        function(tx, r) {
          sendResponse(r.rows.item(0));
        });
    }, function(e) {
      console.log(e.message);
      sendResponse({error: e.message});
    });
};


//when a span will be clicked then showpage will be called with the id if the span 



        this.createTable = function() {
        	if(window.localStorage.getItem("_80162_isTableCreated")!= "true"){
          db_.transaction(function(tx) {
            tx.executeSql("CREATE TABLE ReadingList (id REAL UNIQUE, url TEXT, shortUrl TEXT, title TEXT, fevicon TEXT, content TEXT, origUrl TEXT)", [],
                function(tx) {  //log_.innerHTML = '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">x</button><strong>Hello!! </strong>Welcome to Papr. Just move the mouse pointer over the buttons on top to discover what you can do with it.</div>';
                chrome.extension.getBackgroundPage().user_notify_first("Hi!!","Welcome to Papr. just press 'Pr.' to the right of address bar and  move the  pointer over the buttons at bottom to discover what you can do with it.");
                window.localStorage.setItem("_80162_isTableCreated","true"); },
                self.onError);
          });
          }
        };

        // add record with random values
        this.newRecord = function() {
        
          var num = Math.round(Math.random() * 10000); // random data
          var url;
          var title;
          var fevicon;
          var shortUrl;
          var orig;
          var content;
          chrome.tabs.getSelected(null,function(tab) {
   					 chrome.extension.sendRequest({
      									type: 'savePageRequest',
      										tabID: tab.id,
  										 });
   					
   					  });
   					
   		  
     
          
        };

saveDirect=function(num, url, shortUrl, title, fevicon, content, orig){
console.log(" in saveDirect bef");
db_.transaction(function(tx) {
          console.log("in tx orig");
          console.log(orig);
          console.log("in tx title");
          window.localStorage.setItem(num.toString(),"F");
          console.log(title);
          if(toString(orig)==="undefined" ||toString(orig)===""|| toString(content)=="" || url==="" || title==="New Tab" || toString(title)==="undefined" || content=== "null" || toString(content)===""){console.log("exception tx");window.localStorage.removeItem(num.toString());  return;}
            tx.executeSql("INSERT INTO ReadingList (id, url, shortUrl, title, fevicon, content, origUrl) VALUES (?, ?, ?, ?, ?, ?, ?)", [num, url, shortUrl, title, fevicon, content, orig],
                function(tx, result) {
                //
                  log_.innerHTML = '';
                  self.showRecords();
                  log_.innerHTML = '';
                  chrome.extension.getBackgroundPage().user_notify("Yay!!","Your Page is added to Papr.");
                },
                self.onError);
          });

};


        this.shortenUrl=function(url) {
        	var start=url.search("//");
			start=start+2;
			
			url=url.substring(start);
			
			end=url.search("/");
			short_url=url.substring(0,end);
			return short_url;
        	};

       /* this.updateRecord = function(id, text) {
          db_.transaction(function(tx) {
            tx.executeSql("UPDATE papr SET text = ? WHERE id = ?", [text.innerHTML, id], null, self.onError);
          });
        };
*/

        this.deleteRecord = function(id) {
          db_.transaction(function(tx) {
            tx.executeSql("DELETE FROM ReadingList WHERE id=?", [id],
                function(tx, result) { self.showRecords() }, self.onError);
          });
        };

        // delete table from db
        this.dropTable = function() {
          db_.transaction(function(tx) {
            tx.executeSql("DROP TABLE ReadingList", [],
                function(tx) { self.showRecords() }, self.onError);
          });
        };
      };
      //chk all
checkAll=function(){
      	console.log("inside checkAll");

    	$('input:checkbox').each(function() { console.log("inside each chkbox");this.checked = true; });
		
};
uncheckAll=function(){
      	console.log("inside checkAll");

    	$('input:checkbox').each(function() { console.log("inside each chkbox");this.checked = false; });
		
};
//test code

  	   
  	   
launch = function(){
$(":checked").each(function(){
  	console.log("div clicked!!");
  	var id = $(this).attr('id');
  	console.log("dadasdasda");
  	window.localStorage.removeItem(id.toString());
  	chrome.tabs.create({url: 'showpage.html?id=' + id});
  	});

};

var showBookmarks=function(){
	document.querySelector('#db-results').innerHTML = '';
	dumpBookmarks();
}
//end test code

      //buttons
      document.addEventListener('DOMContentLoaded', function () {
      var db = new DB();
      db.init();
      //document.querySelector('li.settings').addEventListener('click',checkAll);
      document.querySelector('#delete').addEventListener('click',db.deleteitems);
      document.querySelector('#Addpage').addEventListener('click',db.newRecord);
      document.querySelector('#launch').addEventListener('click',launch);
      document.querySelector('#fb_share').addEventListener('click',db.fb_share);
      
      $('#bookmarks').toggle(
      function(){
      showBookmarks();
      $('#bookmarks').attr('title', "Show saved pages");
      },
      function(){
      var db = new DB();
      db.init();
      $('#bookmarks').attr('title', "Show Bookmarks");
      });
      
      $('#settings').toggle(
      function(){
      checkAll();
      $('#settings').attr('title', "Uncheck all");
      },
      function(){
      uncheckAll();
      $('#settings').attr('title', "Checkall");
      });
      // tipsy

    
      $('#Addpage').tipsy({fade: true,gravity: 'nw'});
      $('#delete').tipsy({fade: true,gravity: 's'});
      $('#settings').tipsy({fade: true,gravity: 's'});
      $('#launch').tipsy({fade: true,gravity: 'sw'});
      $('#bookmarks').tipsy({fade: true,gravity: 's'});
      $('#fb_share').tipsy({fade: true,gravity: 'se'});
      $('.red').tipsy({fade: true,gravity: 'w'});
      $('.orange').tipsy({delayIn: 2000,gravity: 'w'});

  
  	    $('.anchor a').click(function(){
  	   console.log("anchor clicked");
  	   id=this.attr('id');
  	   _Url=this.attr('href');
  	   chrome.tabs.create({url: _Url });
  	   window.localStorage.removeItem(id.toString()); 
  	   });
      
      });